package com.vitabuybuy.tv.ui.tencent.liveroom.ui

import android.graphics.BitmapFactory
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.base.appContext
import com.library.common.toast.XToast
import com.library.common.util.JsonUtil
import com.tencent.liteav.demo.beauty.constant.BeautyConstants
import com.tencent.liteav.demo.beauty.model.ItemInfo
import com.tencent.liteav.demo.beauty.model.TabInfo
import com.tencent.liteav.demo.beauty.view.BeautyPanel
import com.tencent.rtmp.TXLiveConstants
import com.tencent.rtmp.ui.TXCloudVideoView
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.adaptebinding.ImageAdapter
import com.vitabuybuy.tv.databinding.MlvbActivityLiveRoomAnchorBinding
import com.vitabuybuy.tv.dialog.SharePopup
import com.vitabuybuy.tv.ui.tencent.liveroom.IMLVBLiveRoomListener
import com.vitabuybuy.tv.ui.tencent.liveroom.MLVBLiveRoom
import com.vitabuybuy.tv.ui.tencent.liveroom.bean.GiftListBean
import com.vitabuybuy.tv.ui.tencent.liveroom.bean.LiveGoodsBean
import com.vitabuybuy.tv.ui.tencent.liveroom.roomutil.commondef.*
import com.vitabuybuy.tv.ui.tencent.liveroom.roomutil.misc.HintDialog
import com.vitabuybuy.tv.ui.tencent.liveroom.roomutil.widget.*
import java.text.SimpleDateFormat
import java.util.*

class AnchorLiveRoomActivity : BaseActivity<LiveRoomViewModel, MlvbActivityLiveRoomAnchorBinding>(),
    IMLVBLiveRoomListener {
    override val isUseBaseTitleBar: Boolean
        get() = false
    override val layoutId: Int
        get() = R.layout.mlvb_activity_live_room_anchor
    private val mPusherList: MutableList<AnchorInfo>? = ArrayList()
    private val mPlayerViews: MutableList<RoomVideoView> = ArrayList()
    private var mChatMsgList: ArrayList<RoomListViewAdapter.TextChatMsg>? = null
    private val mChatMsgGiftAdapter by lazy { ChatMsgGiftAdapter() }
    private var mChatMsgAdapter: RoomListViewAdapter.ChatMessageAdapter? = null
    private val mTextMsgInputDialog by lazy { TextMsgInputDialog(mContext) }
    private val mPutOnGoodsDialog by lazy { PutOnLiveGoofsPopup(mContext) }
    private var mSwipeAnimationController: SwipeAnimationController? = null
    private val mBeautyLevel = 5
    private val mWhiteningLevel = 3
    private val mRuddyLevel = 2
    private val mBeautyStyle = TXLiveConstants.BEAUTY_STYLE_SMOOTH
    private var mPusherMute = false
    private var mMLVBLiveRoom: MLVBLiveRoom? = null
    private var mRoomInfo: RoomInfo? = null

    private var timer: Timer? = null
    private var timerTask: TimerTask? = null

    override fun onGetBundle(bundle: Bundle?) {
        mRoomInfo = bundle?.getSerializable("roomInfo") as RoomInfo
    }

    override fun initView(savedInstanceState: Bundle?) {
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        timer = Timer()
        mMLVBLiveRoom = MLVBLiveRoom.sharedInstance(appContext)
        mMLVBLiveRoom?.setListener(this)
        mBinding.mlvbVideoViewFullScreen.setLogMargin(12f, 12f, 80f, 60f)
        mMLVBLiveRoom?.run {
            startLocalPreview(true, mBinding.mlvbVideoViewFullScreen)
            setCameraMuteImage(
                BitmapFactory.decodeResource(
                    resources, R.drawable.mlvb_pause_publish
                )
            )
            setBeautyStyle(mBeautyStyle, mBeautyLevel, mWhiteningLevel, mRuddyLevel)
            muteLocalAudio(mPusherMute)
            createRoom(mRoomInfo?.roomID, mRoomInfo?.mixedPlayURL, mRoomInfo?.roomInfo, object :
                IMLVBLiveRoomListener.CreateRoomCallback {
                override fun onSuccess(roomId: String) {
                    mRoomInfo?.roomID = roomId
                    ImageAdapter.setCircleImageUrl(
                        mBinding.ivAuthorAvatar, mRoomInfo?.authorAvatar, ContextCompat.getDrawable(
                            mContext,
                            R.drawable.beauty_ic_makeups_widow
                        )
                    )
                    mBinding.tvStoreName.text = mRoomInfo?.authorName
                    viewModel.getLiveDetail(mRoomInfo?.liveId)
                    startTimer()
                }

                override fun onError(errCode: Int, e: String) {
                    errorGoBack(
                        getString(R.string.mlvb_create_live_room_error),
                        errCode, e
                    )
                }
            })
        }
        mBinding.mlvbGiftListView.apply {
            layoutManager = object : LinearLayoutManager(mContext, VERTICAL, false) {
                override fun canScrollVertically(): Boolean {
                    return false
                }

                override fun setStackFromEnd(stackFromEnd: Boolean) {
                    super.setStackFromEnd(true)
                }
            }
            adapter = mChatMsgGiftAdapter
        }
        //美颜p图部分
        val defaultBeauty = mBinding.mlvbLayoutFaceBeauty.defaultBeautyInfo
        defaultBeauty?.beautyBg = BeautyConstants.BEAUTY_BG_GRAY
        mBinding.mlvbLayoutFaceBeauty.setBeautyInfo(defaultBeauty)
        mBinding.mlvbLayoutFaceBeauty.setBeautyManager(mMLVBLiveRoom?.beautyManager)

        mChatMsgList = ArrayList()
        mChatMsgAdapter = RoomListViewAdapter.ChatMessageAdapter(mContext, mChatMsgList)
        mBinding.mlvbChatListView.adapter = mChatMsgAdapter
        mSwipeAnimationController = SwipeAnimationController(mContext)
        mSwipeAnimationController?.setAnimationView(mBinding.mlvbRlChatLayout)

    }

    override fun observeData() {
        viewModel.liveDetils.observe(this, androidx.lifecycle.Observer {
            mBinding.tvAudienceNumber.text = "观众 " + it.viewerQuantity
            mBinding.tvAudienceAllNumber.text = "观众总人数 " + it.viewerQuantity
            mBinding.tvAudienceNowNumber.text = "观众 " + it.onlineQuantity
            mBinding.tvAudienceDianZanNumber.text = "点赞数 " + it.praiseQuantity
            mBinding.tvAudienceGiftNumber.text = "收到礼物 " + it.giftQuantity
        })
        viewModel.goodsList.observe(this, androidx.lifecycle.Observer {
            mPutOnGoodsDialog.initData(it)
            mPutOnGoodsDialog.showPopupWindow()
        })
    }

    private fun startTimer() {
        timerTask = object : TimerTask() {
            var cnt = 0
            override fun run() {
                runOnUiThread {
                    mBinding.tvPlayTime.text =
                        getString(R.string.already_play) + getStringTime(cnt++)
                }
            }
        }
        timer?.schedule(timerTask, 0, 1000)
    }

    private fun getStringTime(cnt: Int): String {
        val hour = cnt / 3600
        val min = cnt % 3600 / 60
        val second = cnt % 60
        return String.format(Locale.CHINA, "%02d:%02d:%02d", hour, min, second);
    }

    override fun eventHandling() {
        mBinding.btnClose.setOnClickListener { onBackPressed() }
        //切换摄像头
        mBinding.mlvbRtmproomCameraSwitcherBtn.setOnClickListener {
            mMLVBLiveRoom?.switchCamera()
        }
        mBinding.mlvbLayoutFaceBeauty.setOnBeautyListener(object : BeautyPanel.OnBeautyListener() {
            override fun onTabChange(tabInfo: TabInfo, position: Int) {}
            override fun onClose(): Boolean {
                mBinding.mlvbLayoutFaceBeauty.visibility =
                    if (mBinding.mlvbLayoutFaceBeauty.visibility == View.VISIBLE) View.INVISIBLE else View.VISIBLE
                mBinding.mlvbLlControllerContainer.visibility =
                    if (mBinding.mlvbLayoutFaceBeauty.visibility == View.VISIBLE) View.INVISIBLE else View.VISIBLE
                return true
            }

            override fun onClick(
                tabInfo: TabInfo, tabPosition: Int,
                itemInfo: ItemInfo, itemPosition: Int
            ): Boolean {
                return false
            }

            override fun onLevelChanged(
                tabInfo: TabInfo, tabPosition: Int,
                itemInfo: ItemInfo, itemPosition: Int,
                beautyLevel: Int
            ): Boolean {
                return false
            }
        })
        mBinding.mlvbRtmproomBeautyBtn.setOnClickListener {
            mBinding.mlvbLayoutFaceBeauty.visibility =
                if (mBinding.mlvbLayoutFaceBeauty.visibility == View.VISIBLE) View.INVISIBLE else View.VISIBLE
            mBinding.mlvbLlControllerContainer.visibility =
                if (mBinding.mlvbLayoutFaceBeauty.visibility == View.VISIBLE) View.INVISIBLE else View.VISIBLE
        }
        //发送消息
        mBinding.mlvbRtmproomChatBtn.setOnClickListener { mTextMsgInputDialog.show() }
        mTextMsgInputDialog.setOnTextSendListener(object : TextMsgInputDialog.OnTextSendListener {
            override fun onTextSend(msg: String?) {
                msg?.run {
                    sendMessage(this)
                }
            }
        })
        mBinding.mlvbChatListView.setOnTouchListener { _, _ ->
            mBinding.mlvbLlControllerContainer.visibility = View.VISIBLE
            mBinding.mlvbLayoutFaceBeauty.visibility = View.INVISIBLE
            false
        }
        mBinding.clParentView.setOnTouchListener { _, event ->
            mBinding.mlvbLlControllerContainer.visibility = View.VISIBLE
            mBinding.mlvbLayoutFaceBeauty.visibility = View.INVISIBLE
            mSwipeAnimationController!!.processEvent(event)
        }
        mBinding.btnGoosList.setOnClickListener {
            viewModel.goodsList.value?.run {
                if (this.isNotEmpty()) {
                    mPutOnGoodsDialog.initData(this)
                    mPutOnGoodsDialog.showPopupWindow()
                } else {
                    viewModel.getGoodsList(mRoomInfo?.liveId)
                }
            } ?: let {
                viewModel.getGoodsList(mRoomInfo?.liveId)
            }
        }
        mPutOnGoodsDialog.onPutOnListener = { it, position ->
            viewModel.putOnLiveGoods(it, mRoomInfo?.liveId, position)
        }
        mBinding.btnShare.setOnClickListener {
            SharePopup(mContext).showPopupWindow()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mMLVBLiveRoom?.stopLocalPreview()
        recycleVideoView()
        timer?.cancel()
        timerTask?.cancel()
    }

    private fun errorGoBack(
        title: String,
        errCode: Int,
        errInfo: String
    ) {
        val errinfo = "$errInfo[$errCode]"
        val spannableStrBuidler = when (errCode) {
            MLVBCommonDef.LiveRoomErrorCode.ERROR_LICENSE_INVALID -> {
                "license 校验失败,请联系管理员"
            }
            MLVBCommonDef.LiveRoomErrorCode.ERROR_NOT_LOGIN -> {
                "用户还没登录"
            }
            MLVBCommonDef.LiveRoomErrorCode.ERROR_NOT_IN_ROOM -> {
                "进入直播间失败"
            }
            MLVBCommonDef.LiveRoomErrorCode.ERROR_PUSH -> {
                "拉流地址错误，或者直播间已关闭"
            }
            MLVBCommonDef.LiveRoomErrorCode.ERROR_PARAMETERS_INVALID -> {
                "license 校验失败,请联系管理员"
            }
            MLVBCommonDef.LiveRoomErrorCode.ERROR_PLAY -> {
                "播放失败"
            }
            MLVBCommonDef.LiveRoomErrorCode.ERROR_IM_FORCE_OFFLINE -> {
                "您的账号在其他地方登录"
            }
            10036 /*IM 创建聊天室数量超过限额错误*/ -> {
                "创建聊天室数量超过限额错误"
            }
            else -> {
                errinfo
            }
        }

        AlertDialog.Builder(mContext)
            .setTitle(title)
            .setMessage(spannableStrBuidler)
            .setCancelable(true)
            .setPositiveButton(getString(R.string.confirm)) { _, _ ->
                mMLVBLiveRoom?.exitRoom(object : IMLVBLiveRoomListener.ExitRoomCallback {
                    override fun onError(errCode: Int, errInfo: String) {}
                    override fun onSuccess() {
                        recycleVideoView()
                        finish()
                    }
                })
            }.show()
    }

    private fun addMessageItem(
        userName: String, message: String,
        aligment: RoomListViewAdapter.TextChatMsg.Alignment
    ) {
        mContext.runOnUiThread {
            val TIME_FORMAT = SimpleDateFormat("HH:mm")
            mChatMsgList?.add(
                RoomListViewAdapter.TextChatMsg(
                    userName, TIME_FORMAT.format(Date()), message, aligment
                )
            )
            mChatMsgAdapter?.notifyDataSetChanged()
            mBinding.mlvbChatListView.post {
                mChatMsgList?.run {
                    mBinding.mlvbChatListView.setSelection(this.size - 1)
                }
            }
        }
    }

    private fun sendMessage(message: String) {
        mMLVBLiveRoom?.sendRoomTextMsg(message, object :
            IMLVBLiveRoomListener.SendRoomTextMsgCallback {
            override fun onError(errCode: Int, errInfo: String) {
                AlertDialog.Builder(
                    mContext,
                    R.style.MlvbRtmpRoomDialogTheme
                ).setMessage(errInfo)
                    .setTitle(getString(R.string.mlvb_send_msg_fail))
                    .setPositiveButton(
                        android.R.string.ok
                    ) { dialog, _ -> dialog.dismiss() }.show()
            }

            override fun onSuccess() {
                val username = when {
                    mRoomInfo?.userName != null -> mRoomInfo?.userName
                    mRoomInfo?.authorName != null -> mRoomInfo?.authorName
                    else -> ""
                }
                username?.let {
                    addMessageItem(
                        it, message,
                        RoomListViewAdapter.TextChatMsg.Alignment.LEFT
                    )
                }
            }
        })
    }

    override fun onBackPressed() {
        AlertDialog.Builder(mContext)
            .setTitle(getString(R.string.reminder))
            .setMessage(getString(R.string.leave_live_and_stop_play))
            .setCancelable(true)
            .setPositiveButton(getString(R.string.confirm)) { _, _ ->
                mMLVBLiveRoom?.exitRoom(object : IMLVBLiveRoomListener.ExitRoomCallback {
                    override fun onError(errCode: Int, errInfo: String) {}
                    override fun onSuccess() {
                        recycleVideoView()
                        finish()
                    }
                })
            }.setNegativeButton(getString(R.string.cancel)) { _, _ -> }.create()
            .show()
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            1 -> {
                XToast.normal(getString(R.string.goods_have_put_on))
                val item = msg.obj as LiveGoodsBean
                viewModel.goodsList.value?.run {
                    this[msg.arg1].isPutOn = true
                }
                mMLVBLiveRoom?.sendRoomCustomMsg(
                    TCMsgModelType.TCMsgModelType_Goods.toString(),
                    JsonUtil.toJson(item),
                    null
                )
            }
        }
    }

    /**
     * 错误回调
     * SDK 不可恢复的错误，一定要监听，并分情况给用户适当的界面提示
     *
     * @param errCode   错误码
     * @param errMsg    错误信息
     * @param extraInfo 额外信息，如错误发生的用户，一般不需要关注，默认是本地错误
     */
    override fun onError(
        errCode: Int, errMsg: String,
        extraInfo: Bundle
    ) {
        errorGoBack("直播间错误", errCode, errMsg)
    }

    /**
     * 警告回调
     *
     * @param warningCode 错误码 TRTCWarningCode
     * @param warningMsg  警告信息
     * @param extraInfo   额外信息，如警告发生的用户，一般不需要关注，默认是本地错误
     */
    override fun onWarning(
        warningCode: Int, warningMsg: String,
        extraInfo: Bundle
    ) {
    }

    override fun onDebugLog(log: String) {}

    /**
     * 房间被销毁的回调
     * 主播退房时，房间内的所有用户都会收到此通知
     *
     * @param roomID 房间ID
     */
    override fun onRoomDestroy(roomID: String) {
        if (mRoomInfo?.createRoom == false) {
            HintDialog.Builder(mContext)
                .setTittle(getString(R.string.mlvb_system_msg))
                .setContent(
                    getString(
                        R.string.mlvb_live_room_destroy,
                        if (mRoomInfo != null) mRoomInfo?.roomInfo else "null"
                    )
                )
                .setButtonText(getString(R.string.mlvb_back))
                .setDismissListener {
                    mMLVBLiveRoom?.exitRoom(object : IMLVBLiveRoomListener.ExitRoomCallback {
                        override fun onError(errCode: Int, errInfo: String) {}
                        override fun onSuccess() {
                            recycleVideoView()
                            finish()
                        }
                    })
                }.show()
        }
    }

    /**
     * 收到新主播进房通知
     * 房间内的主播（和连麦中的观众）会收到新主播的进房事件，您可以调用 [MLVBLiveRoom.startRemoteView] 显示该主播的视频画面。
     *
     * @param anchorInfo 新进房用户信息
     * @note 直播间里的普通观众不会收到主播加入和推出的通知。
     */
    override fun onAnchorEnter(anchorInfo: AnchorInfo) {
        if (anchorInfo.userID == null) {
            return
        }
        val videoView = applyVideoView(anchorInfo.userID) ?: return
        if (mPusherList != null) {
            var exist = false
            for (item in mPusherList) {
                if (anchorInfo.userID.equals(item.userID, ignoreCase = true)) {
                    exist = true
                    break
                }
            }
            if (!exist) {
                mPusherList.add(anchorInfo)
            }
        }
        videoView.startLoading()
        mMLVBLiveRoom?.startRemoteView(anchorInfo, videoView.videoView, object :
            IMLVBLiveRoomListener.PlayCallback {
            override fun onBegin() {
                videoView.stopLoading(
                    mRoomInfo?.createRoom ?: false
                ) //推流成功，stopLoading 大主播显示出踢人的button
            }

            override fun onError(errCode: Int, errInfo: String) {
                onAnchorExit(anchorInfo)
                if (mRoomInfo?.createRoom == true) {
                    mMLVBLiveRoom?.kickoutJoinAnchor(anchorInfo.userID)
                }
            }

            override fun onEvent(event: Int, param: Bundle) {
                //TODO
            }
        })
    }

    /**
     * 收到主播退房通知
     * 房间内的主播（和连麦中的观众）会收到新主播的退房事件，您可以调用 [MLVBLiveRoom.stopRemoteView] 关闭该主播的视频画面。
     *
     * @param anchorInfo 退房用户信息
     * @note 直播间里的普通观众不会收到主播加入和推出的通知。
     */
    override fun onAnchorExit(anchorInfo: AnchorInfo) {
        if (mPusherList != null) {
            val it =
                mPusherList.iterator()
            while (it.hasNext()) {
                val item = it.next()
                if (anchorInfo.userID.equals(item.userID, ignoreCase = true)) {
                    it.remove()
                    break
                }
            }
        }
        mMLVBLiveRoom?.stopRemoteView(anchorInfo) //关闭远端视频渲染
        recycleVideoView(anchorInfo.userID)
    }

    /**
     * 收到观众进房通知
     *
     * @param audienceInfo 进房观众信息
     */
    override fun onAudienceEnter(audienceInfo: AudienceInfo) {
        viewModel.getLiveDetail(mRoomInfo?.liveId)
    }

    /**
     * 收到观众退房通知
     *
     * @param audienceInfo 退房观众信息
     */
    override fun onAudienceExit(audienceInfo: AudienceInfo) {
        viewModel.getLiveDetail(mRoomInfo?.liveId)
    }

    /**
     * 主播收到观众连麦请求时的回调
     *
     * @param anchorInfo 观众信息
     * @param reason     连麦原因描述
     */
    override fun onRequestJoinAnchor(
        anchorInfo: AnchorInfo, reason: String
    ) {
    }

    /**
     * 连麦观众收到被踢出连麦的通知
     * 连麦观众收到被主播踢除连麦的消息，您需要调用 [MLVBLiveRoom.kickoutJoinAnchor] 来退出连麦
     */
    override fun onKickoutJoinAnchor() {}

    /**
     * 收到请求跨房 PK 通知
     * 主播收到其他房间主播的 PK 请求
     * 如果同意 PK ，您需要调用 [MLVBLiveRoom.startRemoteView]  接口播放邀约主播的流
     *
     * @param anchorInfo 发起跨房连麦的主播信息
     */
    override fun onRequestRoomPK(anchorInfo: AnchorInfo) {}

    /**
     * 收到断开跨房 PK 通知
     */
    override fun onQuitRoomPK(anchorInfo: AnchorInfo) {}
    override fun onRecvRoomTextMsg(
        roomid: String,
        userid: String,
        userName: String,
        userAvatar: String,
        message: String
    ) {
        addMessageItem(userName, message, RoomListViewAdapter.TextChatMsg.Alignment.LEFT)
    }

    override fun onRecvRoomCustomMsg(
        roomID: String,
        userID: String,
        userName: String,
        userAvatar: String,
        cmd: String,
        message: String
    ) {
        when (cmd.toInt()) {
            TCMsgModelType.TCMsgModelType_MemberEnterRoom -> {
                addMessageItem(
                    userName,
                    getString(R.string.enter_live_room),
                    RoomListViewAdapter.TextChatMsg.Alignment.CENTER
                )
            }
            TCMsgModelType.TCMsgModelType_MemberQuitRoom -> {
                addMessageItem(
                    userName,
                    getString(R.string.quit_live_room),
                    RoomListViewAdapter.TextChatMsg.Alignment.CENTER
                )
            }
            TCMsgModelType.TCMsgModelType_Praise -> {
                if (mBinding.heartLayout != null) {
                    mBinding.heartLayout.addFavor()
                }
                viewModel.getLiveDetail(mRoomInfo?.liveId)
            }
            TCMsgModelType.TCMsgModelType_DanmaMsg -> {
                val giftBean = JsonUtil.fromJson(message, GiftListBean::class.java)
                giftBean.name = userName
                mChatMsgGiftAdapter.setNewData(listOf(giftBean))
                Handler().postDelayed({
                    if (mChatMsgGiftAdapter.mData.isNotEmpty()) {
                        mChatMsgGiftAdapter.removeAt(mChatMsgGiftAdapter.mData.size - 1)
                    }
                }, 2200)
                viewModel.getLiveDetail(mRoomInfo?.liveId)
            }
        }
    }

    inner class RoomVideoView(
        var videoView: TXCloudVideoView, button: Button,
        loadingBkg: FrameLayout, loadingImg: ImageView
    ) {
        var loadingBkg: FrameLayout
        var loadingImg: ImageView
        var kickButton: Button
        var userID: String? = null

        @JvmField
        var isUsed: Boolean = false
        fun startLoading() {
            kickButton.visibility = View.INVISIBLE
            loadingBkg.visibility = View.VISIBLE
            loadingImg.visibility = View.VISIBLE
            loadingImg.setImageResource(R.drawable.mlvb_linkmic_loading)
            val ad = loadingImg.drawable as AnimationDrawable
            ad.start()
        }

        fun stopLoading(showKickoutBtn: Boolean) {
            kickButton.visibility = if (showKickoutBtn) View.VISIBLE else View.GONE
            loadingBkg.visibility = View.GONE
            loadingImg.visibility = View.GONE
            val ad = loadingImg.drawable as AnimationDrawable
            ad.stop()
        }

        fun stopLoading() {
            kickButton.visibility = View.GONE
            loadingBkg.visibility = View.GONE
            loadingImg.visibility = View.GONE
            val ad = loadingImg.drawable as AnimationDrawable
            ad.stop()
        }

        fun setUsed(used: Boolean) {
            videoView.visibility = if (used) View.VISIBLE else View.GONE
            if (!used) {
                stopLoading(false)
            }
            isUsed = used
        }

        init {
            videoView.visibility = View.GONE
            this.loadingBkg = loadingBkg
            this.loadingImg = loadingImg
            isUsed = false
            kickButton = button
            kickButton.setOnClickListener {
                kickButton.visibility = View.INVISIBLE
                val userID = userID
                if (userID != null) {
                    mPusherList?.run {
                        for (item in this) {
                            if (userID.equals(item.userID, ignoreCase = true)) {
                                onAnchorExit(item)
                                break
                            }
                        }
                        mMLVBLiveRoom?.kickoutJoinAnchor(userID)
                    }
                }
            }
        }
    }

    @Synchronized
    fun applyVideoView(id: String?): RoomVideoView? {
        if (id == null) {
            return null
        }
        for (item in mPlayerViews) {
            if (!item.isUsed) {
                item.setUsed(true)
                item.userID = id
                return item
            } else {
                if (item.userID != null && item.userID == id) {
                    item.setUsed(true)
                    return item
                }
            }
        }
        return null
    }

    @Synchronized
    fun recycleVideoView(id: String) {
        for (item in mPlayerViews) {
            if (item.userID != null && item.userID == id) {
                item.userID = null
                item.setUsed(false)
            }
        }
    }

    @Synchronized
    fun recycleVideoView() {
        for (item in mPlayerViews) {
            item.userID = null
            item.setUsed(false)
        }
    }

    companion object {
        fun openActivity(mContext: BaseActivity<*, *>, roomInfo: RoomInfo?) {
            mContext.startActivity(
                bundleOf(Pair("roomInfo", roomInfo)), AnchorLiveRoomActivity::class.java
            )
        }
    }
}